package com.xinlan.imageeditlibrary.editimage.fragment;

import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import androidx.recyclerview.widget.RecyclerView;

import com.xinlan.imageeditlibrary.BaseEditFragment;
import com.xinlan.imageeditlibrary.EditImageFragment;
import com.xinlan.imageeditlibrary.R;
import com.xinlan.imageeditlibrary.editimage.ModuleConfig;
import com.xinlan.imageeditlibrary.editimage.adapter.StickerPictureAdapter;
import com.xinlan.imageeditlibrary.editimage.model.OnBackPressedCallBack;
import com.xinlan.imageeditlibrary.editimage.task.StickerTask;
import com.xinlan.imageeditlibrary.editimage.utils.BaseUtils;
import com.xinlan.imageeditlibrary.editimage.utils.DensityUtil;
import com.baselibrary.utils.SpacesRightDec;
import com.xinlan.imageeditlibrary.editimage.utils.SpacesTopDec;
import com.xinlan.imageeditlibrary.editimage.view.StickerItem;
import com.xinlan.imageeditlibrary.editimage.view.StickerView;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
 * 贴图分类fragment
 *
 * @author panyi
 */
public class StickerFragment extends BaseEditFragment {
    public static final int INDEX = ModuleConfig.INDEX_STICKER;

    public static final String TAG = StickerFragment.class.getName();
    public static final String STICKER_FOLDER = "stickers";
    private View mMainView;
    private StickerView mStickerView;// 贴图显示控件
    private SaveStickersTask mSaveTask;
    private EditImageFragment mEditImageFragment;
    private RecyclerView mRvStickerPicture;
    private ArrayList<String> pathList = new ArrayList<String>();// 图片路径列表
    private StickerPictureAdapter mStickerPictureAdapter;
    public OnBackPressedCallBack mOnBack;
    public PopupWindow mPopSticker;

    public static StickerFragment newInstance(EditImageFragment mEditImageFragment) {
        StickerFragment fragment = new StickerFragment();
        fragment.setEditImageFragment(mEditImageFragment);
        fragment.setOnBackClick();
        return fragment;
    }


    public void setOnBackClick() {
        mOnBack = new OnBackPressedCallBack() {
            @Override
            public void onBack() {
                backToMain();
            }
        };
    }


    public void setEditImageFragment(EditImageFragment mEditImageFragment) {
        this.mEditImageFragment = mEditImageFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        mMainView = inflater.inflate(R.layout.fragment_edit_image_sticker_type,
                null);
        initData();
        return mMainView;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    private void initData() {
        try {
            String[] files = getActivity().getAssets()
                    .list(STICKER_FOLDER);
            for (String name : files) {
                pathList.add(STICKER_FOLDER + File.separator + name);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        mStickerPictureAdapter = new StickerPictureAdapter(getLayoutInflater());

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (mEditImageFragment != null) {
            this.mStickerView = mEditImageFragment.mStickerView;
        }

        View mPopView = getLayoutInflater().inflate(R.layout.popup_sticker, null);
        mPopSticker = BaseUtils.showPopwindow(activity, mPopView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        mRvStickerPicture = mPopView.findViewById(R.id.rv_sticker_picture);
        mRvStickerPicture.setAdapter(mStickerPictureAdapter);
        mRvStickerPicture.addItemDecoration(new SpacesRightDec(DensityUtil.dip2px(requireContext(), 10)));
        mRvStickerPicture.addItemDecoration(new SpacesTopDec(DensityUtil.dip2px(requireContext(), 10)));
        mStickerPictureAdapter.setStickList(pathList);
        mStickerPictureAdapter.setOnStickerPictureClickListener(new StickerPictureAdapter.OnStickerPictureClickListener() {
            @Override
            public void onStickerPicture(String assetsPath) {
                mPopSticker.dismiss();
                mStickerView.addBitImage(getImageFromAssetsFile(assetsPath));
            }
        });
        mPopView.findViewById(R.id.tv_hidepop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopSticker.dismiss();
                backToMain();
            }
        });
    }

    @Override
    public void onShow() {
        mPopSticker.showAtLocation(mMainView, Gravity.BOTTOM, 0, 0);
        mEditImageFragment.mode = EditImageFragment.MODE_STICKERS;
        mStickerView.setVisibility(View.VISIBLE);
        mRvStickerPicture.setVisibility(View.VISIBLE);
    }

    @Override
    public void backToMain() {
        if (mPopSticker != null && mPopSticker.isShowing())
            mPopSticker.dismiss();
        mEditImageFragment.mode = EditImageFragment.MODE_NONE;
        mEditImageFragment.swFragment(0);
        mRvStickerPicture.setVisibility(View.GONE);
    }

    /**
     * 从Assert文件夹中读取位图数据
     *
     * @param fileName
     * @return
     */
    private Bitmap getImageFromAssetsFile(String fileName) {
        Bitmap image = null;
        AssetManager am = getResources().getAssets();
        try {
            InputStream is = am.open(fileName);
            image = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }

    /**
     * 保存贴图任务
     *
     * @author panyi
     */
    private final class SaveStickersTask extends StickerTask {
        private boolean isToMain;
        private BaseUtils.OnAddStickerAndText onAddStickerAndText;

        public SaveStickersTask(EditImageFragment activity, boolean isToMain, BaseUtils.OnAddStickerAndText onAddStickerAndText) {
            super(activity);
            this.isToMain = isToMain;
            this.onAddStickerAndText = onAddStickerAndText;
        }

        @Override
        public void handleImage(Canvas canvas, Matrix m) {
            LinkedHashMap<Integer, StickerItem> addItems = mStickerView.getBank();
            for (Integer id : addItems.keySet()) {
                StickerItem item = addItems.get(id);
                item.matrix.postConcat(m);// 乘以底部图片变化矩阵
                canvas.drawBitmap(item.bitmap, item.matrix, null);
            }// end for
        }

        @Override
        public void onPostResult(Bitmap result) {
            mStickerView.clear();
            mEditImageFragment.changeMainBitmap(result, true);
            if (isToMain)
                backToMain();
            if (onAddStickerAndText != null)
                onAddStickerAndText.onAddStickerAndText(0);
        }
    }// end inner class

    /**
     * 保存贴图层 合成一张图片
     */
    public void applyStickers(boolean isToMain, BaseUtils.OnAddStickerAndText onAddStickerAndText) {

        if (mStickerView.getBit() == null) {//没有添加贴图
            if (onAddStickerAndText != null) {
                onAddStickerAndText.onAddStickerAndText(0);
            }
            return;
        }
        if (mSaveTask != null) {
            mSaveTask.cancel(true);
        }
        mSaveTask = new SaveStickersTask(mEditImageFragment, isToMain, onAddStickerAndText);
        mSaveTask.execute(mEditImageFragment.getMainBit());
    }
}
